package  com.stars.empoly.update.util

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.File
import java.io.InputStreamReader

object ApkInstallUtil {

    private const val TAG = "ApkInstallUtil"

    fun install(context: Context,apkFile :File){
        val installChmodApk = installChmodApk(apkFile)
        if(installChmodApk){
            return
        }
        installApk(context,apkFile)
    }

    fun installApk(context: Context, apkFile: File){
        val intent = Intent(Intent.ACTION_VIEW).apply {
            this.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val apkUri = FileProvider.getUriForFile(context,
                    Utils.getPackageName() + ".provider",apkFile)
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
                setDataAndType(apkUri,"application/vnd.android.package-archive")
            } else {
                setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive")
            }
        }
        if (intent.resolveActivity(context!!.packageManager) != null) {
            context.startActivity(intent)
        }else{
        }
    }

    /**
     * 命令安装
     */
    private fun installChmodApk(apkFile:File):Boolean{
        val cmd = StringBuffer("chmod 777").apply {
            append(apkFile.getPath() + "\n")
            append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install -r ")
            append(apkFile.getPath() + "\n")
        }.toString()
        val result: Int = cmd(cmd)
        if(result == 0){
            return true
        }else if (result == 1) {
            return false
        }else{
            return false
        }
    }

    /**
     * 执行命令
     *
     * @param cmd
     * @return
     */
    fun cmd(cmd: String?): Int {
        if (cmd == null || cmd.length == 0) {
            return -1
        }
        var process: Process? = null
        var outputStream: DataOutputStream? = null
        var inputReader: BufferedReader? = null
        var errorReader: BufferedReader? = null
        try {
            val runtime = Runtime.getRuntime()
            process = runtime.exec("su")
            outputStream = DataOutputStream(process.outputStream)
            inputReader =
                BufferedReader(InputStreamReader(process.inputStream))
            errorReader =
                BufferedReader(InputStreamReader(process.errorStream))
            outputStream.writeBytes(cmd)
            outputStream.writeBytes("exit \n")
            outputStream.flush()
            val result = process.waitFor()
            val logcat = java.lang.StringBuilder()
            var line: String? = null
            while (inputReader.readLine().also { line = it } != null) {
                logcat.append(line).append("\n")
            }
            while (errorReader.readLine().also { line = it } != null) {
                logcat.append(line).append("\n")
            }
            return result
        } catch (e: java.lang.Exception) {

        } finally {
            if (errorReader != null) {
                try {
                    errorReader.close()
                } catch (e: Throwable) {
                }
            }
            if (inputReader != null) {
                try {
                    inputReader.close()
                } catch (e: Throwable) {
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close()
                } catch (e: Throwable) {
                }
            }
            if (process != null) {
                try {
                    process.destroy()
                } catch (e: Throwable) {
                }
            }
        }
        return -1
    }
}
